package com.yf.serviceImpl;

import com.yf.bean.MessageBean;
import com.yf.dao.MessageDao;
import com.yf.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("MessageServiceImpl")
public class MessageServiceImpl implements MessageService {
    @Autowired
    MessageDao messageDao;

    @Override
    public List<MessageBean> getMsgByUid(Map<String, Object> params) {
        List<MessageBean> msg = messageDao.getMsgByUid(params);
        List<Integer> refIds = new ArrayList<>();
        List<Integer> refMap = new ArrayList<>();
        for (int i = 0; i < msg.size(); i++) {
            Integer ref = msg.get(i).getRef();
            if (ref != null) {
                refIds.add(ref);
                refMap.add(i);
            }
        }
        if (refIds.size() > 0) {
            List<MessageBean> refMsg = messageDao.getMsgById(refIds);
            for (int i = 0; i < refMap.size(); i++) {
                Integer msgIdx = refMap.get(i);
                MessageBean messageBean = msg.get(msgIdx);
                String msgRef = refMsg.get(i).getMsg();
                messageBean.setRefMsg(msgRef);
            }
        }
        return msg;
    }

    @Override
    public int addMessage(MessageBean bean) {
        return messageDao.addMessage(bean);
    }

    @Override
    public int getMsgNum(Integer receiver) {
        return messageDao.getMsgNum(receiver);
    }

    @Override
    public int getMsgNumUnRead(Integer receiver) {
        return messageDao.getMsgNumUnRead(receiver);
    }

    @Override
    public boolean setMsgStatus(Integer id, Integer status) {
        if (status == 1) {
            return messageDao.setMessageRead(id) > 0;
        }

        if (status == 2) {
            return messageDao.setMessageDisabled(id) > 0;
        }
        return false;
    }
}
